<?php
/**
 * Created by PhpStorm.
 * User: fdg296
 * Date: 2017/7/25
 * Time: 17:13
 */
namespace backend\controllers;

use backend\models\AuthRule;
use Yii;
use yii\web\AdminController;
use backend\models\Menu;

class SysMenuController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'SysMenu';

    public function actionIndex(){
        $list = Menu::find()->orderBy(array('sort'=>SORT_ASC))->asArray()->all();

        foreach($list as &$value){
            $value['html'] = '';
        }

        $list_tree = \common\helps\tools::getCustomerTree($list,0,0);
        $this->saveLog($this->service,'菜单管理页','VIEW','');                     //日志

        return $this->render('index',['data_list'=>$list_tree]);
    }

    public function actionAddMenu(){
        $model = new Menu();
        $data = Yii::$app->request->post();
        $data_now['name'] = $data['name'];
        $data_now['app'] = $data['app'];
        $data_now['action'] = $data['action'];
        $data_now['model'] = $data['model'];
        $data_now['type'] = $data['type'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];;
        //前端没有设置ICON，处理默认值
        if(!isset($data['icon']) || $data['icon'] == ''){
            $data_now['icon'] = 'circle-o';
        }else{
            $data_now['icon'] = $data['icon'];
        }
        $data_now['data'] = $data['data'];
        $data_now['parent_id'] = $data['parent_id'] == '' ? 0 : $data['parent_id'];
        $data_now['status'] = $data['status'];
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['remark'] = $data['remark'];

        $transaction = Yii::$app->db->beginTransaction();
        try{
            //添加菜单
            $res = Yii::$app->db->createCommand()->insert('j_menu',$data_now)->execute();
            $result_id = Yii::$app->db->getLastInsertID();
            if(!$res){
                throw new \Exception('操作失败');
            }
            //添加权限规则
            $role['module'] = $data_now['app'];
            $role['param'] = $data_now['data'];
            $role['title'] = $data_now['name'];
            $role['menu_id'] = $result_id;
            $role['status'] = 1;
            $role['name'] = '/'. strtolower($data_now['model']).'/'. strtolower($data_now['action']);
            $one_data = AuthRule::find()->where(array('name'=>$role['name']))->asArray()->all();
            if(!empty($one_data)){
                throw new \Exception('该规则已存在!');
            }

            $ret = Yii::$app->db->createCommand()->insert('j_auth_rule',$role)->execute();
            if(!$ret){
                throw new \Exception('操作失败');
            }

            $transaction->commit();
            $this->saveLog($this->service,'添加菜单','ADD', $data_now['name'] . "\r\n" .\yii\helpers\Json::encode($data_now));                     //日志
            $this->retJson('添加成功',200);
        }catch(\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson('操作失败',500);
        }
    }

    /**
     * 编辑菜单
     */
    public function actionUpdateMenu(){
        $model = new Menu();
        $data = Yii::$app->request->post();
        $data_now['name'] = $data['name'];
        $data_now['app'] = $data['app'];
        $data_now['action'] = $data['action'];
        $data_now['model'] = $data['model'];
        $data_now['type'] = $data['type'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];
        //前端没有设置ICON，处理默认值
        if(!isset($data['icon']) || $data['icon'] == ''){
            $data_now['icon'] = 'circle-o';
        }else{
            $data_now['icon'] = $data['icon'];
        }
        $data_now['data'] = $data['data'];
        $data_now['parent_id'] = $data['parent_id'] == '' ? 0 : $data['parent_id'];
        $data_now['status'] = $data['status'];
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['remark'] = $data['remark'];

        $transaction = Yii::$app->db->beginTransaction();
        try{
            //添加菜单
            $res = $model::updateAll($data_now, " id = ".$data['menu_id']);

            if(!$res){
                throw new \Exception('操作失败');
            }
            //添加权限规则
            $role['module'] = $data_now['app'];
            $role['param'] = $data_now['data'];
            $role['title'] = $data_now['name'];
            $role['menu_id'] = $data['menu_id'];
            $role['status'] = 1;
            $role['name'] = '/'. strtolower($data_now['model']).'/'. strtolower($data_now['action']);
            $one_data = AuthRule::find()->where(array('name'=>$role['name']))->asArray()->one();
            if(!empty($one_data) && $one_data['menu_id'] != $data['menu_id']){
                throw new \Exception('该规则已存在!');
            }

            $role['edit_time'] = date('Y-m-d H:i:s',time());
            $ret = AuthRule::updateAll($role, " menu_id = ".$data['menu_id']);
            if(!$ret){
                throw new \Exception('操作失败');
            }

            $transaction->commit();
            $this->saveLog($this->service,'编辑菜单','MOD','编辑菜单:'. $data_now['name'] . "\r\n" .\yii\helpers\Json::encode($data_now));                     //日志
            $this->retJson('编辑成功',200);
        }catch(\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    public function actionDisable(){

    }

    public function actionEnable(){

    }

    /**
     * 删除菜单
     */
    public function actionDelMenu(){
        $model = new Menu();
        $data = Yii::$app->request->post();
        $where = ' id = '.$data['id'].' or parent_id = '.$data['id'];
        $list = $model::find()->where($where)->select('id')->asArray()->all();
        $data_list = array_column($list,'id');
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $res = $model::deleteAll($where);
            if(!$res){
                throw new \Exception('操作失败');
            }

            $map = ['menu_id'=>$data_list];
            $ret = AuthRule::deleteAll($map);
            if(!$ret){
                throw new \Exception('操作失败');
            }

            $transaction->commit();
            $this->retJson('操作成功',200);
        }catch(\Exception $e){
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }

    /*
     * 根据id获取菜单信息
     */
    public function actionGetOneMenu(){
        $data = Yii::$app->request->post();

        $result = Menu::findOne(array('id'=>$data['id']));
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 局部关闭csrf
     * action 方法名
     */
    public function beforeAction($action){

        $currentaction = $action->id;

        $novalidactions = ['disable','enable','del-menu','add-menu','update-menu','get-one-menu'];

        if(in_array($currentaction,$novalidactions)) {

            $action->controller->enableCsrfValidation = false;

        }
        parent::beforeAction($action);

        return true;
    }
}